package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import view.MeetingsView;
import view.ViewHelpers;
import model.AppModel;

import model.Email;
import model.EmailBuilder;
import model.Meeting;
import model.ModelException;

/**
 * This class controls the  Meeting View
 * 
 * Controller assigns events of creating/ editing and deleting a 
 * meeting and specifies the actions to invoke upon triggering these events. 
 * @author buthainahaldosary
 * @since May 31, 2013
 *
 * @version $Revision: 1.0 $
 */
public class MeetingsController {
		/**
		 *  Application model and view
		 */
		private AppModel model;
		
		/**
		 *  The view to work on
		 */
		private MeetingsView view;
	
		/**
		 * Constructor 
		 * @param model the main application model to work on
		 */
	public MeetingsController(AppModel model) {
	
		this.model=model;
		setupView();
		assignHotkeys();
		refreshView();
		assignHandlersToEvents();
		view.showDialog();	
	}

	/**
	 * Loads meetings list into view
	 */
private void refreshView() {
	
	view.getNavigationView().getMeetings().removeAllElements();

	for (Meeting meeting : model.getUser().getMeetings()){
		view.getNavigationView().getMeetings().addElement(meeting.getTopic());
	}
			
		}

/**
 * Method that initializes a new meetings view
 */
	private void setupView() {
		view=new MeetingsView();	
	}
	/**
	 * Method that assigns hot keys to new meeting/ edit / delete buttons
	 */
	private void assignHotkeys() {
		view.getNavigationView().getNewMeeting().setMnemonic(KeyEvent.VK_M);
		view.getPreviewView().getEditBtn().setMnemonic(KeyEvent.VK_E);
		view.getPreviewView().getDeleteBtn().setMnemonic(KeyEvent.VK_D);
		
	}
/**
 * Method that registers and assigns handlers to events 
 */
	private void assignHandlersToEvents() {
		//new meeting
		view.getNavigationView().getNewMeeting().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(!model.isConnected())
					ViewHelpers.alertError("Please make sure you are connected before attempting to create a meeting.");
				else
				actionNewMeeting();
			}
		});
		
		//edit meeting
		view.getPreviewView().getEditBtn().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				actionEditMeeting();
			}
		});
		
		//delete meeting
		view.getPreviewView().getDeleteBtn().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				actionDeleteMeeting();
			}
		});
		
		//meeting selected
		view.getNavigationView().getMeetingsList().addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				previewMeeting();
			}
		});
		
		
		
	}
	/**
	 * Loads the selected meeting in the listing view
	 */
	protected void previewMeeting() {
		Meeting firstSelectedMeeting = getSelectedMeeting();
		if (firstSelectedMeeting != null){
			previewMeeting(firstSelectedMeeting);
		}
	
}
/**
 * Sets the fields of the meeting in the preview pane

 * @param selectedMeeting Meeting
 */
	private void previewMeeting(Meeting selectedMeeting) {
		view.getPreviewView().setLocation(selectedMeeting.getLocation());
		view.getPreviewView().setTopic(selectedMeeting.getTopic());
		view.getPreviewView().setAttendees(selectedMeeting.getAttendees());
		view.getPreviewView().setStartDate(selectedMeeting.getStart());
		view.getPreviewView().setEndDate(selectedMeeting.getEnd());
		view.getPreviewView().setDescriptionText(selectedMeeting.getDescription());
		
	}
/**
 * finds the meeting object given the selected value from the JList

 * @return meeting object */
	private Meeting getSelectedMeeting() {
		
		if (view.getNavigationView().getMeetingsList().getSelectedValue() == null){
			return null;
		}
	
		String selectedMeeting = view.getNavigationView().getMeetingsList().getSelectedValue().toString();
		List<Meeting> meetings=model.getUser().getMeetings();
		Meeting currentMeeting=null;
		for(Meeting mt:meetings)
		{
			if(mt.getTopic().toLowerCase().trim().equals(selectedMeeting.toLowerCase().trim()))
			{
				currentMeeting=mt;
				return currentMeeting;
			}
		}
		
		return null;
	}

	/**
	 * Method that is triggered when a delete meeting button is clicked
	 */
	protected void actionDeleteMeeting() {
		String meetingTitle = (String) view.getNavigationView().getMeetingsList().getSelectedValue();
		if (meetingTitle == null){
			ViewHelpers.alertError("Please select a meeting to delete");
			return;
		}
		int option = JOptionPane.showConfirmDialog (null, "Are you sure you want to delete the selected meetings?");
		
		
		//get meeting object
		String title = (String) view.getNavigationView().getMeetingsList().getSelectedValue();
		Meeting m = null;
		for (Meeting meeting : model.getUser().getMeetings()){
			if (meeting.getTopic().trim().equalsIgnoreCase(meetingTitle)){
				m= meeting;
				break;
			}
		}
	
		
		
		if (option == JOptionPane.YES_OPTION ) {
			try {
				int id = m.getId();
				model.getUser().deleteMeeting(id);
				//send email to each recipient
				//String recipientList=m.getAttendees();
				// extract each recipient
				//List<String> recipients = Arrays.asList(recipientList.split(","));
				//create email for each recipient
				String body="";
				java.util.Date date= new java.util.Date();
				 Timestamp currentTime = new Timestamp(date.getTime());
				//for (String recipient : recipients)
				//{
					//recipient=recipient.trim();
					body="Hello "+m.getAttendees()+"\n The meeting "+m.getTopic()+" has been deleted by "+model.getUser().getName()+" which includes you. Here are the details:\n"+
					"~~~\n"+
							"Hash: "+
				"Start time: "+m.getStart().toGMTString()+"\n "+
							"End time: "+ m.getEnd().toGMTString()+"\n"+
				"Topic: " +m.getTopic()+"\n Description: "+ m.getDescription()+"\n Other attendees: "+ m.getAttendees()+"\n Thank you.";
				int folderId= model.getUser().getFolder("Outbox").getId();			
				Email emailToSend =  new EmailBuilder().setFrom(model.getUser().getName()).setTo(m.getAttendees()).setSubject("Deletion of meeting: "+m.getTopic()).setRead(false).setBody(body).setFolderId(folderId).build();
				emailToSend.save();
				model.getUser().getFolder("Outbox").getEmails().add(emailToSend);	
				refreshView();
			}
			//} 
				catch (ModelException e) {
				ViewHelpers.alertError("Could not delete the meeting.");
				e.printStackTrace();
			}
		}
	}
		
		
	

	/**
	 * Method that is triggered when an edit meeting button is clicked
	 */
	protected void actionEditMeeting() {
		

		String meetingTitle = (String) view.getNavigationView().getMeetingsList().getSelectedValue();
		if(meetingTitle == null)
		{
			ViewHelpers.alertError("Please select a meeting to edit");
			return;
		}
		Meeting m = null;
		for (Meeting meeting : model.getUser().getMeetings()){
			if (meeting.getTopic().trim().equalsIgnoreCase(meetingTitle)){
				m= meeting;
				break;
			}
		}
	
		new EditMeetingController(model,m);
		refreshView();
		
	}

	/**
	 * Method that is triggered when a new meeting button is clicked
	 */
	protected void actionNewMeeting() {
		new NewMeetingController(model,null);
		refreshView();
		
		
	}

}
